package org.example.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.example.erp.domain.*;
import org.example.erp.service.WarehouseAreaService;
import org.example.erp.service.WarehouseLocationService;
import org.example.erp.service.WarehouseService;
import org.example.erp.service.impl.WmIssueHeaderServiceImpl;
import org.example.erp.service.impl.WmIssueLineServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class WmIssueHeaderController {
    @Autowired
    private WmIssueHeaderServiceImpl wmIssueHeaderService;

    @Resource
    private WmIssueLineServiceImpl salesOrderService;

    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private WarehouseAreaService warehouseAreaService;
    @Autowired
    private WarehouseLocationService warehouseLocationService;
    @GetMapping("/productionPicking/find")
    public DataResult findSalesOutbound(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String issueCode,
            @RequestParam(required = false) String issueName,
            @RequestParam(required = false) String warehouseName,
            @RequestParam(required = false) String issueDate,
            @RequestParam(required = false) String status) {

        Page<WmIssueHeader> page = new Page<>(currentPage, pageSize);
        QueryWrapper<WmIssueHeader> wrapper = new QueryWrapper<>();

        // 将字符串日期转换为 Date 类型（如果需要）
        Date parsedIssueDate = null;
        if (StringUtils.hasText(issueDate)) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 根据实际情况调整格式
                parsedIssueDate = dateFormat.parse(issueDate);
            } catch (ParseException e) {
                return DataResult.error("Invalid date format");
            }
        }

        // 构建查询条件
        wrapper.lambda()
                .like(StringUtils.hasText(issueCode), WmIssueHeader::getIssueCode, issueCode)
                .like(StringUtils.hasText(issueName), WmIssueHeader::getIssueName, issueName)
                .like(StringUtils.hasText(warehouseName), WmIssueHeader::getWarehouseName, warehouseName)
                .eq(parsedIssueDate != null, WmIssueHeader::getIssueDate, parsedIssueDate)
                .eq(StringUtils.hasText(status), WmIssueHeader::getStatus, status);

        try {
            page = wmIssueHeaderService.page(page, wrapper);
            return DataResult.success(page);
        } catch (Exception e) {
            // 记录异常详情
            return DataResult.error("An error occurred while processing the request.");
        }
    }
    @DeleteMapping("/productionPicking/delete")
    public DataResult delete(@RequestBody List<Integer> issueId) {
        if(issueId.isEmpty()){
            wmIssueHeaderService.remove(null);
        }else{
            wmIssueHeaderService.removeByIds(issueId);
        }
        return DataResult.success();
    }

    @PostMapping("/productionPicking/insert")
    public DataResult insert(@RequestBody WmIssueHeader s) {
        try {
            List<String> warehouseNames = s.getWarehouseNames();
            // 查询仓库
            QueryWrapper<Warehouse> q1 = new QueryWrapper<>();
            q1.lambda().eq(Warehouse::getWarehouseId, warehouseNames.get(0));
            Warehouse one = warehouseService.getOne(q1);
            if (one == null) {
                return DataResult.error("未找到对应的仓库");
            }

            // 查询库区
            QueryWrapper<WarehouseArea> q2 = new QueryWrapper<>();
            q2.lambda().eq(WarehouseArea::getWarehouseAreaId, warehouseNames.get(1));
            WarehouseArea one1 = warehouseAreaService.getOne(q2);
            if (one1 == null) {
                return DataResult.error("未找到对应的库区");
            }

            // 查询库位
            QueryWrapper<WarehouseLocation> q3 = new QueryWrapper<>();
            q3.lambda().eq(WarehouseLocation::getWarehouseLocationCode, warehouseNames.get(2));
            WarehouseLocation one2 = warehouseLocationService.getOne(q3);
            if (one2 == null) {
                return DataResult.error("未找到对应的库位");
            }

            // 更新 picking 对象中的详细信息
            s.setWarehouseId(Long.valueOf(one.getWarehouseId()));
            s.setWarehouseName(one.getWarehouseName());
            s.setWarehouseCode(one.getWarehouseCode());

            s.setAreaId(Long.valueOf(one1.getWarehouseAreaId()));
            s.setAreaName(one1.getWarehouseAreaName());
            s.setAreaCode(one1.getWarehouseAreaCode());

            s.setLocationId(Long.valueOf(one2.getWarehouseLocationId()));
            s.setLocationCode(one2.getWarehouseLocationCode());
            s.setLocationName(one2.getWarehouseLocationName());

            boolean save = wmIssueHeaderService.save(s);
            // 保存 picking 记录
            if (!save) {
                return DataResult.error("保存失败");
            }
            return DataResult.success(save?"成功":"失败");
        } catch (Exception e) {
            return DataResult.error("新增失败：" + e.getMessage());
        }
    }

    @PutMapping("/productionPicking/update")
    public DataResult updateReversoContexts(@RequestBody WmIssueHeader s) {
        System.out.println("============================================================" + s);
        boolean b = wmIssueHeaderService.updateById(s);
        if (!b) {
            return DataResult.error("更新失败");
            }
        return DataResult.success(b? "成功" : "失败");
    }


    @PutMapping("/productionPickingzt/updateStatus")
    public DataResult updatePickingStatus() {

            return DataResult.success();
    }


}
